package io.github.ali.commons.lock;

import io.github.ali.commons.lock.exception.LockException;

/**
 * 分布式锁
 *
 * @author fuli
 */
public interface Locker {

    /**
     * 加锁
     *
     * @param key
     * @param value
     * @return 成功:true; 失败:false
     */
    default boolean tryLock(String key, String value) {
    	return tryLock(key, value, 0, 0, 0);
    }

    default boolean tryLock(String key, String value, long expiring) {
    	return tryLock(key, value, expiring, 0, 0);
    }

    default boolean tryLock(String key, String value, int tryTimes, long tryGap) {
    	return tryLock(key, value, 0, tryTimes, tryGap);
    }

    /**
     * @param key
     * @param value
     * @param expiring 过期时间（秒）
     * @param tryTimes 重试次数
     * @param tryGap   重试时间间隔（毫秒）
     * @return
     */
    boolean tryLock(String key, String value, long expiring, int tryTimes, long tryGap);

    /**
     * 加锁,只要不抛异常就是成功
     *
     * @param key
     * @param value
     * @throws LockException
     */
    default void lock(String key, String value) throws LockException{
    	lock(key, value, 0, 0, 0);
    }

    default void lock(String key, String value, long expiring) throws LockException{
    	lock(key, value, expiring, 0, 0);
    }

    default void lock(String key, String value, int tryTimes, long tryGap) throws LockException{
    	lock(key, value, 0, tryTimes, tryGap);
    }

    /**
     * @param key
     * @param value
     * @param expiring 过期时间（秒）
     * @param tryTimes 重试次数
     * @param tryGap   重试时间间隔（毫秒）
     * @throws LockException
     */
	void lock(String key, String value, long expiring, int tryTimes, long tryGap) throws LockException;

    /**
     * 解锁
     *
     * @param key
     */
    void unlock(String key, String value);
}
